<template>
  <div class="map">
    <van-nav-bar title="地图找房" left-arrow @click-left="$router.back()" />
    <div id="container"></div>
  </div>
</template>

<script>
import { getMap } from '@/api/area'
import { getAreas } from '@/utils/storage'
export default {
  data() {
    return {}
  },
  async mounted() {
    const { BMapGL } = window
    const map = new BMapGL.Map('container')
    const city = JSON.parse(getAreas())

    const cityName = city ? city.label + '市' : '北京市'
    map.centerAndZoom(cityName, 12) // 初始化地图,设置中心点坐标和地图级别
    map.enableScrollWheelZoom(true) // 开启鼠标滚轮缩放
    const res = await getMap(city.value)
    // console.log(res)
    res.data.body.forEach((item) => {
      const point = new BMapGL.Point(item.coord.longitude, item.coord.latitude)
      const content = item.label + '<br>' + item.count + '套'
      const label = new BMapGL.Label(content, {
        // 创建文本标注
        position: point, // 设置标注的地理位置
        offset: new BMapGL.Size(10, 20) // 设置标注的偏移量
      })
      map.addOverlay(label) // 将标注添加到地图中
      label.setStyle({
        // 设置label的样式
        width: '60px',
        height: '60px',
        lineHeight: '20px',
        paddingTop: '10px',
        textAlign: 'center',
        color: '#fff',
        backgroundColor: 'orange',
        fontSize: '14px',
        borderRadius: '50%',
        border: '1px solid #fff'
      })
      label.addEventListener('click', async function () {
        const point = new BMapGL.Point(item.coord.longitude, item.coord.latitude)
        map.centerAndZoom(point, 14)
        map.clearOverlays()
        const res = await getMap(item.value)
        console.log(res)

        res.data.body.forEach((item) => {
          const point = new BMapGL.Point(
            item.coord.longitude,
            item.coord.latitude
          )
          const content = item.label + '<br>' + item.count + '套'
          const label = new BMapGL.Label(content, {
            // 创建文本标注
            position: point, // 设置标注的地理位置
            offset: new BMapGL.Size(10, 20) // 设置标注的偏移量
          })
          map.addOverlay(label) // 将标注添加到地图中
          label.setStyle({
            // 设置label的样式
            width: '60px',
            height: '60px',
            lineHeight: '20px',
            paddingTop: '10px',
            textAlign: 'center',
            color: '#fff',
            backgroundColor: 'orange',
            fontSize: '14px',
            borderRadius: '50%',
            border: '1px solid #fff'
          })
        })
      })
    })

    const scaleCtrl = new BMapGL.ScaleControl() // 添加比例尺控件
    map.addControl(scaleCtrl)
    const zoomCtrl = new BMapGL.ZoomControl() // 添加缩放控件
    map.addControl(zoomCtrl)
    const cityCtrl = new BMapGL.CityListControl() // 添加城市列表控件
    map.addControl(cityCtrl)
  },
  methods: {},
  components: {}
}
</script>

<style scoped lang="less">
.van-nav-bar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 999;
}
#container {
  height: 100vh;
}
</style>
